/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.fb.admin.controller;
import com.fb.common.ActionData;
import com.fb.common.ActionType;
import com.fb.common.CommonUtil;
import com.fb.common.ConfigFactory;
import com.fb.common.NewsCateData;
import com.fb.common.NewsData;
import com.fb.common.Re_News_NewsCate_Data;
import com.fb.common.RenderModel;
import com.fb.common.UserData;
import com.fb.common.UserRole;
import com.fb.model.ActionModel;
import com.fb.model.NewsCateModel;
import com.fb.model.NewsModel;
import com.fb.model.Re_News_NewsCate_Model;
import com.fb.model.SessionModel;
import com.fb.model.UserModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javaxt.io.Image;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class AdminNewsController extends HttpServlet {
    private static final Logger logger = Logger.getLogger(AdminNewsController.class);
    private static final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    public static final String STATIC_UPLOAD_IMAGE = ConfigFactory.getParam("upload", "upload_path") + ConfigFactory.getParam("upload", "upload_image");
    public static final String STATIC_UPLOAD_VIDEO = ConfigFactory.getParam("upload", "upload_path") + ConfigFactory.getParam("upload", "upload_video");
    public static final String STATIC_URL_IMAGE = ConfigFactory.getParam("static", "img") + ConfigFactory.getParam("upload", "upload_image");
    public static final String STATIC_URL_VIDEO = ConfigFactory.getParam("static", "img") + ConfigFactory.getParam("upload", "upload_video");
    //public static final String REMOTE_POST_PATH = ConfigFactory.getParam("upload", "upload_post");
    //public static final String STATIC_POST_PATH = ConfigFactory.getParam("static", "img") + ConfigFactory.getParam("upload", "upload_post");
    private static final int NEWS_PER_PAGE = 10;
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }
    
    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            if (!CommonUtil.checkSession(req, resp)) {
                return;
            }
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("AdminNewsController.handle:" + ex.getMessage(), ex);
        }
    }
    
    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch (pathInfo) {            
            case "/ajax-edit":
                content = ajaxEdit(req, resp);
                break;
            case "/ajax-add":
                content = ajaxAdd(req, resp);
                break;
            case "/ajax-delete":
                content = ajaxDelete(req, resp);
                break;
            case "/ajax-upload-image":
                content = ajaxUploadImage(req, resp);
                break;
            case "/ajax-upload-video":
                content = ajaxUploadVideo(req, resp);
                break;
            case "/add":
                content = renderAddPage(req, resp);
                break;
            case "/edit":
                content = renderEditPage(req, resp);
                break;
            case "/search":
                content = renderSearchPage(req, resp);
                break;                
            default:
                content = renderIndexPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }
    
    
    
    
    private String renderIndexPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.NEWS)) {
                resp.sendRedirect("/");
                return "";
            }

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req)); 
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "news_edit"));            
            dic.setVariable("PAGE_TITLE", "Danh sách tin tức");
                        
            int page = 1;
            String p = req.getParameter("p") == null ? "1" : req.getParameter("p");
            try {
                page = Integer.parseInt(p);
            } catch (NumberFormatException e) {
            }
            
            
            NewsModel newsModel = NewsModel.getInstance();
            List<NewsData> lstNewsData = newsModel.getNews((page - 1) * NEWS_PER_PAGE, NEWS_PER_PAGE);  
            Re_News_NewsCate_Model modelRe = Re_News_NewsCate_Model.getInstance();
            NewsCateModel newsCateModel = NewsCateModel.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
            if (lstNewsData != null && !lstNewsData.isEmpty()) {
                for (NewsData newsData : lstNewsData) {
                    
                    TemplateDataDictionary section = dic.addSection("LIST_NEWS");
                    section.setVariable("AUTHOR", String.valueOf(newsData.getAuthor()));
                    section.setVariable("NEWS_ID", newsData.getId());  
                    section.setVariable("NEWS_TITLE", newsData.getTitle());  
                    String listCate = "";
                    List<Re_News_NewsCate_Data> listOfCurrentNews = modelRe.getItemsByNewsId(newsData.getId());
                    for(Re_News_NewsCate_Data item : listOfCurrentNews){                        
                        NewsCateData newsCateData = newsCateModel.getNewsCateById(item.getIdNewsCate());
                        listCate += newsCateData.getName() + ", ";
                    }
                    if(!listCate.equals(""))
                        listCate = listCate.substring(0, listCate.length() - 2);
                    section.setVariable("CATES_NAME", listCate);  
                    Date d = new Date(newsData.getCreated());
                    section.setVariable("CREATED", sdf.format(d));
                    if (newsData.getStatus() == 0) {
                        section.setVariable("STATUS", "Chờ duyệt");
                        section.showSection("WARNING");
                    } else if (newsData.getStatus() == 1){
                        section.setVariable("STATUS", "Công khai");
                    }
                    else {
                        section.setVariable("STATUS", "Ẩn");
                        section.showSection("DANGER");
                    } 
                }
            }
            
            UserModel userModel = UserModel.getInstance();
            List<UserData> userList = userModel.getUser(0, -1);
            for (UserData userData : userList) {
                TemplateDataDictionary section = dic.addSection("USER_LIST");
                section.setVariable("USER_ID", userData.getId());
                section.setVariable("USER_NAME", userData.getUsername());                
            }

            List<NewsCateData> lstNewsCate = newsCateModel.getCate(0, -1);
            if (lstNewsCate != null && !lstNewsCate.isEmpty()) {
                for (NewsCateData newsCateData : lstNewsCate) {
                    TemplateDataDictionary section = dic.addSection("CATE_LIST");
                    section.setVariable("CATE_ID", String.valueOf(newsCateData.getId()));
                    section.setVariable("CATE_NAME", newsCateData.getName());
                }
            }
             
            int count = newsModel.getNews(0, -1).size();
            String pageNavi = CommonUtil.getPageNavi(page, count, NEWS_PER_PAGE, "");
            dic.setVariable("PAGENAVI", pageNavi);
            
            
            Template template = RenderModel.getAdminCTemplate("news_list");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminNewsController.renderIndexPage: " + ex.getMessage(), ex);
        }
        return content;
    }
    
    
    
    private String renderSearchPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.NEWS_SEARCH)) {
                return CommonUtil.toPermissionDenied();
            }

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req)); 
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "news_edit"));            
            dic.setVariable("PAGE_TITLE", "Danh sách tin tức");
                        
            int page = 1;
            String p = req.getParameter("p") == null ? "1" : req.getParameter("p");
            try {
                page = Integer.parseInt(p);
            } catch (NumberFormatException e) {
            }
            
            String id_Search = req.getParameter("postID") != null ? req.getParameter("postID") : "";
            String user = req.getParameter("postUser") != null ? req.getParameter("postUser") : "";
            String title = req.getParameter("postTitle") != null ? req.getParameter("postTitle") : "";
            String cate = req.getParameter("postCate") != null ? req.getParameter("postCate") : "";
            String created = req.getParameter("postCreated") != null ? req.getParameter("postCreated") : "";
            String status = req.getParameter("postStatus") != null ? req.getParameter("postStatus") : "";              
            String userSearch = "";
            if(!user.equals("")){
                UserModel userModelSearch = UserModel.getInstance();
                UserData userDataSearch = userModelSearch.getUserById(user);
                userSearch = userDataSearch.getUsername();
            }
            
            NewsModel newsModel = NewsModel.getInstance();
            List<NewsData> lstNewsData = newsModel.getNews(0, -1, userSearch, title, status, id_Search, created, cate);  
            Re_News_NewsCate_Model modelRe = Re_News_NewsCate_Model.getInstance();
            NewsCateModel newsCateModel = NewsCateModel.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
            if (lstNewsData != null && !lstNewsData.isEmpty()) {
                //for (NewsData newsData : lstNewsData) 
                for(int i = (page - 1) * NEWS_PER_PAGE; i < page * NEWS_PER_PAGE; i++){ 
                    if(i == lstNewsData.size())
                        break;
                    NewsData newsData = lstNewsData.get(i);
                    List<Re_News_NewsCate_Data> listOfCurrentNews = modelRe.getItemsByNewsId(newsData.getId());
                        TemplateDataDictionary section = dic.addSection("LIST_NEWS");
                        section.setVariable("AUTHOR", String.valueOf(newsData.getAuthor()));
                        section.setVariable("NEWS_ID", newsData.getId());  
                        section.setVariable("NEWS_TITLE", newsData.getTitle());  
                        String listCate = "";

                        for(Re_News_NewsCate_Data item : listOfCurrentNews){                        
                            NewsCateData newsCateData = newsCateModel.getNewsCateById(item.getIdNewsCate());
                            listCate += newsCateData.getName() + ", ";
                        }
                        listCate = listCate.substring(0, listCate.length() - 2);
                        section.setVariable("CATES_NAME", listCate);  
                        Date d = new Date(newsData.getCreated());
                        section.setVariable("CREATED", sdf.format(d));
                        if (newsData.getStatus() == 0) {
                            section.setVariable("STATUS", "Chờ duyệt");
                            section.showSection("WARNING");
                        } else if (newsData.getStatus() == 1){
                            section.setVariable("STATUS", "Công khai");
                        }
                        else {
                            section.setVariable("STATUS", "Ẩn");
                            section.showSection("DANGER");
                        }                                      
                }
            }
            
            UserModel userModel = UserModel.getInstance();
            List<UserData> userList = userModel.getUser(0, -1);
            for (UserData userData : userList) {
                TemplateDataDictionary section = dic.addSection("USER_LIST");
                section.setVariable("USER_ID", userData.getId());
                section.setVariable("USER_NAME", userData.getUsername()); 
                if(user.equals(userData.getId()))
                    section.showSection("USER_SELECTED");
            }

            dic.setVariable("ID_SEARCH", id_Search);
            dic.setVariable("TITLE_SEARCH", title);
            
            List<NewsCateData> lstNewsCate = newsCateModel.getCate(0, -1);
            if (lstNewsCate != null && !lstNewsCate.isEmpty()) {
                for (NewsCateData newsCateData : lstNewsCate) {
                    TemplateDataDictionary section = dic.addSection("CATE_LIST");
                    section.setVariable("CATE_ID", String.valueOf(newsCateData.getId()));
                    section.setVariable("CATE_NAME", newsCateData.getName());
                    if(newsCateData.getId().equals(cate))
                        section.showSection("CATE_SELECTED");
                }
            }
            
            dic.setVariable("CREATE_SEARCH", created);            
            if (status.equals("0")) 
                dic.showSection("WAITING");            
            else if (status.equals("1"))
                dic.showSection("PUBLISH");            
            else if(status.equals("2"))
                dic.showSection("INACTIVE");
            
            int count = lstNewsData.size();
            String pageNavi = CommonUtil.getPageNavi(page, count, NEWS_PER_PAGE, "?" + req.getQueryString());
            dic.setVariable("PAGENAVI", pageNavi);
            
            Template template = RenderModel.getAdminCTemplate("news_list");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminNewsController.renderIndexPage: " + ex.getMessage(), ex);
        }
        return content;
    }
    
    
    private String renderAddPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.NEWS_ADD)) {
                resp.sendRedirect("/");
                return "";
            }
            
            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "news_add"));            
            dic.setVariable("PAGE_TITLE", "Thêm mới tin tức");
            dic.showSection("ADD_PAGE");
            dic.showSection("ACTIVE_YES");
            dic.showSection("NO_THUMB");
            NewsCateModel newsCateModel = NewsCateModel.getInstance();
            List<NewsCateData> listNewsCate = newsCateModel.getCate(0, -1);
            if (listNewsCate != null && !listNewsCate.isEmpty()) {
                for (NewsCateData cateData : listNewsCate) {
                    TemplateDataDictionary section = dic.addSection("NEWSCATE_LIST");
                    section.setVariable("NEWSCATE_ID", String.valueOf(cateData.getId()));
                    section.setVariable("NEWSCATE_NAME", cateData.getName());
                }
            }
            
            if (CommonUtil.checkAccess(req, UserRole.NEWS_ADD)) {
                dic.showSection("OP_PUBLISH");
            }
            
            Template template = RenderModel.getAdminCTemplate("news_add");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminNewsController.renderAddPage: " + ex.getMessage(), ex);
        }
        return content;
    }
    
    
    
    private String renderEditPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "news_edit"));
            dic.setVariable("PAGE_TITLE", "Cập nhật tin tức");
            dic.showSection("EDIT_PAGE");

            String id = req.getParameter("id") != null ? req.getParameter("id") : "";
            if (id.isEmpty()) {
                resp.sendRedirect("/news");
                return "";
            }       
            
            NewsModel newsModel = NewsModel.getInstance();
            NewsData newsData = newsModel.getNewsById(id);
            if (newsData != null) {                
                dic.setVariable("NEWS_ID", newsData.getId());
                dic.setVariable("NEWS_TITLE", newsData.getTitle());
                String time = formatter.format(newsData.getTime());
                dic.setVariable("NEWS_TIME", time);
                if (newsData.getStatus() == 0) {
                    dic.showSection("WAITING");
                } else if (newsData.getStatus() == 1){
                    dic.showSection("PUBLISH");
                }
                else dic.showSection("INACTIVE");
                
                NewsCateModel newsCateModel = NewsCateModel.getInstance();
                List<NewsCateData> listNewsCate = newsCateModel.getCate(0, -1);
                if (listNewsCate != null && !listNewsCate.isEmpty()) {
                    Re_News_NewsCate_Model modelRe = Re_News_NewsCate_Model.getInstance();
                    List<Re_News_NewsCate_Data> listOfCurrentNews = modelRe.getItemsByNewsId(id);
                    for (NewsCateData cateData : listNewsCate) {
                        TemplateDataDictionary section = dic.addSection("NEWSCATE_LIST");
                        section.setVariable("NEWSCATE_ID", String.valueOf(cateData.getId()));
                        section.setVariable("NEWSCATE_NAME", cateData.getName());
                        //show cate checked
                        for(Re_News_NewsCate_Data dt : listOfCurrentNews){
                            if(dt.getIdNewsCate().equals(cateData.getId()))
                                section.showSection("CATE_CHECKED");
                        }
                    }
                }
                dic.setVariable("NEWS_SOURCE", newsData.getSource());
                
                
                String image = newsData.getImage();
                if (image.isEmpty()) {
                    dic.showSection("NO_THUMB");
                } else {
                    dic.showSection("HAS_THUMB");
                    dic.setVariable("IMAGE_SRC", STATIC_URL_IMAGE + image);
                    dic.setVariable("IMAGE_NAME", image);
                }
                
                
                dic.setVariable("NEWS_DESC", newsData.getDesc());
                dic.setVariable("NEWS_CONTENT", newsData.getContent());
                dic.setVariable("NEWS_EDITOR", newsData.getEditor());
                dic.setVariable("NEWS_AUTHOR", newsData.getAuthor());                               
                String updated = formatter.format(newsData.getUpdated());
                String created = formatter.format(newsData.getCreated());
                dic.setVariable("NEWS_UPDATED", updated);
                dic.setVariable("NEWS_CREATED", created);
                dic.showSection("UPDATE_INFO");      
                if (CommonUtil.checkAccess(req, UserRole.NEWS_EDIT)) {
                    dic.showSection("NEWS_EDIT");
                    dic.showSection("OP_PUBLISH");
                }
                                
                                
                Template template = RenderModel.getAdminCTemplate("news_add");
                content = template.renderToString(dic);
            } else {
                resp.sendRedirect("/news");
                return "";
            }
        } catch (Exception ex) {
            logger.error("AppsController.renderEditPage: " + ex.getMessage(), ex);
        }

        return content;
    }
    
    
    
    private String ajaxAdd(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.checkAccess(req, UserRole.NEWS_ADD)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Thêm tin tức thành công.";
        Map<String, String> data = new HashMap<>();
        try {
                String title = "";
                String slug = CommonUtil.URLFriendly(title);
                long time = 0;
                String status = "0";
                List<String> lstCats = new ArrayList<>();
                String desc = "";
                String scontent = "";
                String source = "";
                String image = "";
                FileItem fileImage = null;
                
                DiskFileItemFactory factory = new DiskFileItemFactory();
                ServletContext servletContext = this.getServletConfig().getServletContext();
                File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
                factory.setRepository(repository);
                ServletFileUpload upload = new ServletFileUpload(factory);
                List<FileItem> items = upload.parseRequest(req);

                Iterator<FileItem> iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = iter.next();
                    String name = item.getFieldName();
                    if (item.isFormField()) {
                        String value = item.getString("UTF-8");
                        switch (name) {
                            case "newsTitle":
                                title = value;
                                break;
                            case "newsTime":
                                if (!value.isEmpty()) {
                                    Date date = formatter.parse(value);
                                    time = date.getTime();
                                }
                                else
                                    time = System.currentTimeMillis();
                                break;
                            case "newsStatus":
                                status = value;
                                break;
                            case "newsCate":
                                lstCats.add(value);
                                break;
                            case "newsSource":
                                source = value;
                                break;
                            case "newsDesc":
                                desc = value;
                                break;
                            case "newsContent":
                                scontent = value;
                                break;
                        }
                    } 
                    else {
                        if (name.equalsIgnoreCase("newsImage")) {
                            String fileName = item.getName();
                            String contentType = item.getContentType();
                            if (!contentType.startsWith("image/")) {
                                msg = "Chỉ được phép upload hình jpg, png, gif.";
                                error = -1;
                            }
                            long sizeInBytes = item.getSize();
                            if (sizeInBytes > 1024 * 1000) {
                                msg = "Kích thước tối đa 1 MB.";
                                error = -1;
                            }
                            image = (System.currentTimeMillis() / 1000) + "_" + fileName.toLowerCase();
                            image = image.substring(0, image.length() - 4) + ".jpg";
                            fileImage = item;
                        }
                    }
                }
                if (title.equalsIgnoreCase("")) {
                    msg = "Tiêu đề tin tức không được trống.";
                    error = -1;
                }
                if (error == 0) {
                    SessionModel sessionModel = SessionModel.getInstance();                
                    String author = sessionModel.getUserLogin(req);
                    NewsModel newsModel = NewsModel.getInstance();

                    NewsData newsData = new NewsData(title, slug, desc, scontent, time, author, Short.parseShort(status), source, image);
                    String newsId = newsModel.addNews(newsData);

                    if (!newsId.isEmpty()) {
                        for(String cate : lstCats){
                            Re_News_NewsCate_Data dataRe = new Re_News_NewsCate_Data(newsId, cate);
                            Re_News_NewsCate_Model modelRe = Re_News_NewsCate_Model.getInstance();
                            modelRe.addItems(dataRe);
                        }
                        data.put("id", newsId);
                        saveThumb(fileImage, image);
                        ActionModel actionModel = ActionModel.getInstance();
                        actionModel.addAction(req, author, ActionType.NEWS_ADD, newsId, title);
                    }     
                }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg, data);
        return content;
    }
    
    
    
    
    private String ajaxEdit(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.checkAccess(req, UserRole.NEWS_EDIT)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Cập nhật tin tức thành công.";
        Map<String, String> data = new HashMap<>();
        try {
            String newsId = "";
            String title = "";
            String slug = CommonUtil.URLFriendly(title);
            long time = 0;
            String status = "0";
            List<String> lstCats = new ArrayList<>();
            String desc = "";
            String scontent = "";
            String source = "";
            String image = "";
            String imageOld = "";
            FileItem fileImage = null;

            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(req);

            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                String name = item.getFieldName();
                if (item.isFormField()) {
                    String value = item.getString("UTF-8");
                    switch (name) {
                        case "newsId":
                            newsId = value;
                            break;                            
                        case "newsTitle":
                            title = value;
                            break;
                        case "newsTime":
                            if (!value.isEmpty()) {
                                Date date = formatter.parse(value);
                                time = date.getTime();
                            }
                            else
                                time = System.currentTimeMillis();
                            break;
                        case "newsStatus":
                            status = value;
                            break;
                        case "newsCate":
                            lstCats.add(value);
                            break;
                        case "newsSource":
                            source = value;
                            break;
                        case "newsDesc":
                            desc = value;
                            break;
                        case "newsContent":
                            scontent = value;
                            break;  
                        case "imageOld":
                            imageOld = value;
                            break;    
                    }
                } 
                else {
                    if (name.equalsIgnoreCase("newsImage")) {
                        String fileName = item.getName();
                        String contentType = item.getContentType();
                        if (!contentType.startsWith("image/")) {
                            msg = "Chỉ được phép upload hình jpg, png, gif.";
                            error = -1;
                        }
                        long sizeInBytes = item.getSize();
                        if (sizeInBytes > 1024 * 1000) {
                            msg = "Kích thước tối đa 1 MB.";
                            error = -1;
                        }
                        image = (System.currentTimeMillis() / 1000) + "_" + fileName.toLowerCase();
                        image = image.substring(0, image.length() - 4) + ".jpg";
                        fileImage = item;
                    }
                }
            }
            if (title.equalsIgnoreCase("")) {
                msg = "Tiêu đề tin tức không được trống.";
                error = -1;
            }
            
            if (error == 0) {
                SessionModel sessionModel = SessionModel.getInstance();                
                String author = sessionModel.getUserLogin(req);
                NewsModel newsModel = NewsModel.getInstance();
                NewsData newsEdit = newsModel.getNewsById(newsId);
                String titleEdit = newsEdit.getTitle();
                image = fileImage == null ? imageOld : image;
                NewsData newsData = new NewsData(newsId, title, slug, desc, time, scontent, author, Short.parseShort(status), source, image);                
                boolean updateNews = newsModel.updateNews(newsData);
                if (!updateNews) {
                    error = -1;
                    msg = "Có lỗi xảy ra.";
                }
                else{
                    Re_News_NewsCate_Model modelRe = Re_News_NewsCate_Model.getInstance();
                    modelRe.deleteItemsByIdNews(newsId);
                    for(String cate : lstCats){
                            Re_News_NewsCate_Data dataRe = new Re_News_NewsCate_Data(newsId, cate);                            
                            modelRe.addItems(dataRe);
                    }
                    //data.put("id", String.valueOf(updateNews)); 
                    saveThumb(fileImage, image);
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, author, ActionType.NEWS_EDIT, newsId, titleEdit);
                }                
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg, data);
        return content;
    }
    
    
    
    
    private String ajaxDelete(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.checkAccess(req, UserRole.NEWS_EDIT)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Xoá tin tức thành công.";
        try {
            String id = req.getParameter("id") != null ? req.getParameter("id") : "";
            if (id.isEmpty()) {
                msg = "Id tin tức không được trống.";
                error = -1;
            } else {
                SessionModel sessionModel = SessionModel.getInstance();
                String userLogin = sessionModel.getUserLogin(req);
                
                NewsModel newsModel = NewsModel.getInstance();
                NewsData newsData = newsModel.getNewsById(id);
                String title = newsData.getTitle();
                boolean addApps = newsModel.deleteNews(id);                
                if (!addApps) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                }
                else{
                    deleteThumb(newsData.getImage());
                    Re_News_NewsCate_Model modelRe = Re_News_NewsCate_Model.getInstance();
                    modelRe.deleteItemsByIdNews(id);
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, userLogin, ActionType.NEWS_DELETE, id, title);
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg);
        return content;
    }
    
    
    private void saveThumb(FileItem fileImage, String image_pa) throws Exception {
        if (fileImage != null) {
            Image image = new Image(fileImage.get());
            image.resize(250, 250);
            int w = image.getWidth() > 250 ? 250 : image.getWidth();
            int h = image.getHeight() > 250 ? 250 : image.getHeight();
            image.crop(0, 0, w, h);

            BufferedImage bi = CommonUtil.convertPNGToJPG(image.getBufferedImage());
            String localPath = STATIC_UPLOAD_IMAGE + image_pa;
            File uploadedFile = new File(localPath);
            ImageIO.write(bi, "jpg", uploadedFile);
        }
    }
    
    
    private void deleteThumb(String thumb) {
        if (thumb == null || thumb.isEmpty()) {
            return;
        }
        String localPath = STATIC_UPLOAD_IMAGE + thumb;
        File file = new File(localPath);
        if (file.exists()) {
            file.delete();
            logger.info("Delete image success");
        }
    }
    
    
    
    private String ajaxUploadImage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        int error = 0;
        String msg = "Upload hình thành công.";
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(req);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (!item.isFormField()) {
                    String name = item.getFieldName();
                    if (name.equalsIgnoreCase("postImage")) {
                        String fileName = item.getName();
                        String contentType = item.getContentType();
                        if (!contentType.startsWith("image/")) {
                            msg = "Chỉ được phép upload hình jpg, png, gif.";
                            error = -1;
                        }
                        long sizeInBytes = item.getSize();
                        if (sizeInBytes > 1024 * 1000) {
                            msg = "Kích thước tối đa 1 MB.";
                            error = -1;
                        }
                        String postImage = (System.currentTimeMillis() / 1000) + "_" + fileName.toLowerCase();
                        // crop and resize
                        if (item != null) {
                            Image image = new Image(item.get());
                            BufferedImage bi = image.getBufferedImage();
                            if (!postImage.endsWith(".jpg")) {
                                bi = CommonUtil.convertPNGToJPG(bi);
                            }
                            String localPath = STATIC_UPLOAD_IMAGE + postImage;
                            //String remotePath = REMOTE_POST_PATH + postImage;
                            File uploadedFile = new File(localPath);
                            ImageIO.write(bi, "jpg", uploadedFile);
                            // put to FTP 
                            //CommonUtil.putImageToFTP(localPath, remotePath);
                            postImage = STATIC_URL_IMAGE + postImage;
                            content = "<script>top.$('.mce-btn.mce-open').parent().find('.mce-textbox').val('" + postImage + "').closest('.mce-window').find('.mce-primary').click();</script>";
                        }
                    }
                }
            }
            if (error == 0) {

            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
//        content = CommonModel.toJSON(error, msg, data);
        return content;
    }
    
    
    
    private String ajaxUploadVideo(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        int error = 0;
        String msg = "Upload video thành công.";
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(req);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (!item.isFormField()) {
                    String name = item.getFieldName();
                    if (name.equalsIgnoreCase("postVideo")) {
                        String fileName = item.getName();
                        fileName = fileName.replace(" ", "-");
                        String postVideo = (System.currentTimeMillis() / 1000) + "_" + fileName.toLowerCase();
                        // crop and resize
                        if (item != null) {
                            String localPath = STATIC_UPLOAD_VIDEO + postVideo;
                            //String remotePath = REMOTE_VIDEO_PATH + postVideo;
                            File uploadedFile = new File(localPath);
                            item.write(uploadedFile);
                            
                            // put to FTP 
                            //CommonUtil.putImageToFTP(localPath, remotePath);
                            postVideo = STATIC_URL_VIDEO + postVideo;
                            content = "<script>top.$('.mce-btn.mce-open').parent().find('.mce-textbox').val('" + postVideo + "')/*.closest('.mce-window').find('.mce-primary').click()*/;</script>";
                        }
                    }
                }
            }
            if (error == 0) {

            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
//        content = CommonModel.toJSON(error, msg, data);
        return content;
    }
}
